package henu.innovation.controller;

import henu.innovation.entity.Exam;
import henu.innovation.entity.Student;
import henu.innovation.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;


    /***
     * 学生登录
     * @param sno 学号
     * @param sname 姓名
     * @param session
     * @return student_main/index
     */
    @RequestMapping("/student_login")
    public ModelAndView login(String sno, String sname, HttpSession session){
        ModelAndView mv = new ModelAndView();
        Student student = studentService.login(sno,sname);
        System.out.println(sno + ":" + sname);
        if(student != null){
            session.setAttribute("studentid",student.getId());
            session.setAttribute("studentnumber",student.getNumber());
            session.setAttribute("studentname",student.getName());
            return studentMain(session);
        }else{
            mv.addObject("msg","学号或姓名有误！");
            mv.setViewName("redirect:/index.jsp");
        }
        return mv;
    }

    @RequestMapping("student_main")
    public ModelAndView studentMain(HttpSession session){
        ModelAndView mv = new ModelAndView("Student/student_main");
        mv.addObject("exampaper",session.getAttribute("exampaper"));
        return mv;
    }

    @RequestMapping("student_exam_listdir")
    public ModelAndView studentExamListdir(HttpSession session){
        ModelAndView mv = new ModelAndView("Student/student_exam_listdir");
        mv.addObject("file",getUploadList(session));
        return mv;
    }

    /**
     * 得到学生上传目录下的文件列表
     * @param session session
     * @return list
     */
    public List<File> getUploadList(HttpSession session){
        String uploadPath = session.getServletContext().getRealPath("/WEB-INF/upload");
        List<File> list = new ArrayList<>();
        uploadPath += "\\" +session.getAttribute("examname") + "\\"+session.getAttribute("studentnumber") + session.getAttribute("studentname");
        File file = new File(uploadPath);
        String[] tempList = file.list();
        File f;
        if(tempList != null){
            for(String s:tempList){
                System.out.println("查看文件的路径："+uploadPath + "\\" + s);
                f = new File(uploadPath + "\\" + s);
                list.add(f);
            }
        }
        return list;
    }
}
